<template>
    <div>
      <!-- //面包学导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/nav/home' }">主页</el-breadcrumb-item>
  
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
  
        <el-breadcrumb-item :to="{ path: '/nav/system/role' }">角色管理</el-breadcrumb-item>
  
      </el-breadcrumb>
  
      <!-- 筛选 -->
      <div class="filter"> </div>
      <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState" @finish="onFinish">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :name="'input'" :label="'角色'">
              <a-input v-model:value="formState['input']"></a-input>
  
            </a-form-item>
          </a-col>
          <a-col  :span="12">
            <a-form-item :name="`createtime`" :label="`创建时间`">
              <a-range-picker v-model:value="formState['createtime']" value-format="YYYY-MM-DD" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin: 0 8px" @click="restform(formRef.resetFields())" >重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <!-- 操作选择 -->
     <div> 
      <a-button type="primary" ghost  @click="showDrawer" >新增</a-button>
      <a-button type="primary" ghost style="margin: 0px 5px;" @click="delUser">删除</a-button>
      <a-dropdown>
      <template #overlay>
        <a-menu @click="handleMenuClick">
          <a-menu-item key="密码重置">密码重置</a-menu-item>
          <a-menu-item key="导出Excl">导出Excl</a-menu-item>
         
        </a-menu>
      </template>
      <a-button>
        更多操作
        <DownOutlined />
      </a-button>
    </a-dropdown>
    </div>
    <!-- 表格 -->
    <a-table :row-selection="rowSelection" :columns="columns" :data-source="data"  :pagination="pagination"  @change="handleTableChange" rowKey="roleId" :customRow="click">
      <template #bodyCell="{ column, text ,record}">
        <template v-if="column.dataIndex === 'name'">
          <a>{{ text }}</a>
        </template>
        <template v-else-if="column.dataIndex == 'status'">
          <span slot="action " slot-scope="text,record">
            <a-tag
              :color="record.status === '1' ? 'green'  : 'red'"
            >
                {{ record.status=="1"?"有效":"锁定" }}
            </a-tag>
          </span>
        </template>
        <template v-else-if="column.dataIndex == 'change'">
            <img src="../../assets/imgs/设置.png" alt="" style="width:15px" @click="changeUser(record)">  
            <img src="../../assets/imgs/眼睛.png" alt="" style="margin-left: 5px;width: 20px;" @click="eyesee(record)">
          <setting-outlined />
          <eye-outlined />
         
        </template>
  
      </template>
    </a-table>
    <!-- 抽屉 -->
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      style="color: red"
      :title='switchs==false ? "新增角色":"修改角色"' 
      placement="right"
      @after-visible-change="afterVisibleChange"
    >
    <!-- 抽屉表单 -->
  
    <a-form
      :model="DrawerformState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="DraweronFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="角色名称"
        name="roleName"
       
      >
        <a-input v-model:value="DrawerformState.roleName" />
      </a-form-item>
  
      <a-form-item
        label="角色描述"
        name="remark"
       
      >
      <a-textarea v-model:value="DrawerformState.remark" placeholder="" :rows="4" />
      </a-form-item>
  
     
      <a-form-item
        label="权限选择"
        name="menuId"
        
      >
    <a-tree
    v-if="treeData.length>0"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    v-model:checkedKeys="checkedKeys"
    checkable
    :tree-data="treeData"
    :defaultExpandAll="true"
    :blokeNode="true"
    
  >
    <template #title="{ title, key }">
      <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
      <template v-else>{{ title }}</template>
    </template>
  </a-tree>
      </a-form-item>
  
  
     
  
      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" >取消</a-button>
        <a-button type="primary" html-type="submit" style="margin-left: 10px;">提交</a-button>
      </a-form-item>
    </a-form>
    </a-drawer>
  
    <!-- 眼睛对话框 -->
    <div>
    
    
    </div>
  
  
    </div>
  
  </template>
  
  <script  setup>
  import { ElMessage } from "element-plus";
  import { reactive, ref ,computed, defineComponent,onMounted,createVNode,watch} from 'vue';
  import { DownOutlined, UpOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import {userApi,createUserApi,deluserApi,changeuserApi} from "../../apis/user";
  import {getRoleApi,RoleMenuApi,getallMenuApi,CreateRoleApi,delRoleApi } from "../../apis/role.js";
  


  import { Modal } from 'ant-design-vue';



//部门树形选择
const checkedKeys = ref([]);


const treeData = ref([] );
  const DrawerformState = ref({
      roleName: '',
      remark: '',
        menuId:''
  
      });
  const serachDate=ref({
    roleName:"",
    // deptId:'',
    createTimeFrom:'',
    createTimeTo:""
  })
  const pagination = ref ({
        total: 200,
        current: 1,
        pageSize: 10
      });
  const expand = ref(false);
  const formRef = ref();
  const formState = reactive({
  });
  onMounted(()=>{
    getAllUser()
    getallMean()
  })
  //得到所有的菜单树形字段
  async function getallMean(){
      let data=await getallMenuApi()
      console.log("树形权限字段",data)
        treeData.value=data.rows.children


  }


  //开关值判断是新增用户还是编辑用户
  const switchs=ref(false);
   //编辑用户
    async function changeUser(column){

     


   const data=await RoleMenuApi(column.roleId)

      console.log("角色菜单",data)

      console.log('123',column);



      switchs.value=true
      DrawerformState.value.roleName= column.roleName
      DrawerformState.value.remark= column.remark 
      checkedKeys.value= data
     
        
    console.log('DrawerformState.value.userId', DrawerformState.value.userId)
  
  
    
  
      showDrawer()
      //回显数据
       
  
    }
  
    
  
  
  //表格
  const columns= ref([
    {
      title: '角色  ',
      
      dataIndex: 'roleName',
      sorter: {
        compare: (a, b) => a.roleName.length - b.roleName.length,
        multiple: 1,
      },
    },
  
    {
      title: '描述',
      key:'1',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      key:'2',
      dataIndex: 'createTime',
    },
    {
      title: '修改时间',
      key:'3',
      dataIndex: 'modifyTime',
    },
    {
      title: '操作',
      
      dataIndex: 'change',
    },
  ]);
  const data = ref([
    // {
    //   key: '1',
    //   username: 'John Brown',
    //   age: 32,
    //   address: 'New York No. 1 Lake Park',
    // },
    // {
    //   key: '2',
    //   username: 'Jim Green',
    //   age: 42,
    //   address: 'London No. 1 Lake Park',
    // },
    // {
    //   key: '3',
    //   username: 'Joe Black',
    //   age: 32,
    //   address: 'Sidney No. 1 Lake Park',
    // },
    // {
    //   key: '4',
    //   name: 'Disabled User',
    //   age: 99,
    //   address: 'Sidney No. 1 Lake Park',
    // },
  ]);
   //拿到所有的用户
   async  function getAllUser(){
       const res=await getRoleApi({pageSize:pagination.value.pageSize,pageNum:pagination.value.current})
      console.log("用户数据",res);
      data.value=res.rows
      
      pagination.value.total=res.total
        
  
        console.log("data.vale",data.value); 
    }
  
  
  //表单值
  const onFinish =async values => {
    console.log('Received values of form: ', values);
  
    if(values.createtime){
      serachDate.value.createTimeFrom=values.createtime[0]
      serachDate.value.createTimeTo=values.createtime[1]
    }
    
    serachDate.value.roleName=values.input
    // serachDate.value.deptId=values.department
   
  
  
   let res= await getRoleApi(serachDate.value)
   console.log("搜索数据",res);
  
   data.value=res.rows
      
      pagination.value.total=res.total
        
  
  
  };
    // 重置表单
    async function restform(){
      // formRef.resetFields()
   
      const res=await getRoleApi({})
    data.value=res.rows
      
      pagination.value.total=res.total
    
   
  }
  
  
  
    // /计算属性
  
   
  
  //选择是否导出
  const handleMenuClick = e => {
        console.log('click', e);
      };
  
    //表格
  
    //定义一个删除列表
  
    //定义删除id
    const  deluserId=ref([])
    const dellist=ref([])
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          dellist.value=selectedRows
          dellist.value=dellist.value.map(m=>m.roleName)
          deluserId.value=selectedRows.map(m=>m.roleId)
  
          console.log("删除id",deluserId.value)
         console.log('dellist.value',dellist.value);
  
        },
        getCheckboxProps: (record) => ({
          // disabled: record.name === 'Disabled User', // Column configuration not to be checked
          name: record.name,
        }),
      };
      //删除用户
      function delUser(){
        console.log(123);
          const notie=dellist.value.join()
        Modal.confirm({
          title: '确定删除角色?',
          icon: createVNode(ExclamationCircleOutlined),
          content: notie,
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            console.log('OK',deluserId.value);
  
            delRoleApi(deluserId.value)
            .then((res)=>{
                console.log("删除了吗",res);
                getAllUser()
                ElMessage.success("删除成功")
            })
  
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      
  
  
  
      }
  
      //分页
        
        
     
      const handleTableChange = (current, pageSize,filters
      ) => {
          console.log('current',current);
          console.log('999',pagination.value.current);
          pagination.value.current=current.current
          pagination.value.pageSize=current.pageSize
          console.log('filters',filters);
          getAllUser()
      };
  
  
      //抽屉
      const visible = ref(false);
  
  const afterVisibleChange = (bool) => {
    console.log('visible', bool);
    if(bool==false){
      switchs.value=false
  
      //重置数据
      DrawerformState.value.roleName=""
      DrawerformState.value.remark= "" 
      checkedKeys.value= "" 
     
    }
    
  };
  
  const showDrawer = () => {
    
    visible.value = true;
  };
    //  抽屉表单
    
      const DraweronFinish = async(values) => {
     
  
  
  
        console.log('Success:', values);
      
        const data=await CreateRoleApi(values)
          console.log("新增角色",data)
          ElMessage.success("新增成功")
        getAllUser()
      };
      
      
  
  
  
  
      const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
      };
  
      
      const treeData2= ref([
        {
          title: '管理员',
          value: '1',
        },
        {
          title: '注册用户',
          value: '2',
         
        },
        {
          title: '普通用户',
          value: '3',
         
        },
        {
          title: '商户',
          value: '4',
         
        },
        {
          title: 'chole',
          value: '5',
         
        },
      ]);

      //树形控件的值
      const expandedKeys = ref(['0-0-0', '0-0-1']);
    const selectedKeys = ref(['0-0-0', '0-0-1']);
   
    watch(expandedKeys, () => {
      console.log('expandedKeys', expandedKeys);



    });
    watch(selectedKeys, () => {
      console.log('selectedKeys', selectedKeys);
    });
    watch(checkedKeys, () => {
      console.log('checkedKeys', checkedKeys._rawValue);
      //监听到树形选择的值，在赋值给表单提交
        DrawerformState.value.menuId=checkedKeys._rawValue


    });


  
        //眼睛对话框
    function eyesee(record){
      console.log("查看",record);
    }
  
  </script>
      
  <style lang="scss">
  .filter {
    margin-top: 20px;
  }
  
  #components-form-demo-advanced-search .ant-form {
    max-width: none;
  }
  
  #components-form-demo-advanced-search .search-result-list {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 2px;
    background-color: #fafafa;
    min-height: 200px;
    text-align: center;
    padding-top: 80px;
  }
  
  [data-theme='dark'] .ant-advanced-search-form {
    background: rgba(255, 255, 255, 0.04);
    border: 1px solid #434343;
    padding: 24px;
    border-radius: 2px;
  }
  
  [data-theme='dark'] #components-form-demo-advanced-search .search-result-list {
    border: 1px dashed #434343;
    background: rgba(255, 255, 255, 0.04);
  }
  
  
  
  </style>